package com.ebank.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ebank.model.MD5Encrypt;

public class LoginCL extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;char=utf-8");
		PrintWriter out =response.getWriter();
		HttpSession session=request.getSession();
		String username=request.getParameter("username");
		String passwd=request.getParameter("passwd");
		String MD5pw = MD5Encrypt.MD5_Ent.MD5(passwd);     
		Statement stat = null;
		Connection con=null;
		ResultSet rs=null;
		PreparedStatement pst = null;
		String selectSQL = "select * from account ";

		try {
			 Class.forName("com.mysql.jdbc.Driver");
			 con = DriverManager.getConnection(
				      "jdbc:mysql://localhost/user?useUnicode=true&characterEncoding=Big5",
				      "root","root");
			 pst=con.prepareStatement("select * from account where username=? and passwd=?");
			 pst.setObject(1, username);
//			 pst.setObject(2, passwd);
			 pst.setObject(2, MD5pw);
		     rs=pst.executeQuery();	
		    
			if(rs.next()){
				session.setAttribute("username", username);
				out.print("Loading....");
				 response.setHeader("refresh", "2;URL=Main");
			}else{
				request.setAttribute("err", "username or password is incorrect!");
				request.getRequestDispatcher("/Login").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(rs!=null){
				try {
					rs.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				rs=null;
			}
			if(pst!=null){
				try {
					pst.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				pst=null;
			}
			if(con!=null){
				try {
					con.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				con=null;
			} 
		
		}
}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
	}

}
